package paf.exporter;

import java.awt.Component;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import paf.model.Connection;
import paf.model.DiagramExpressionModel;
import paf.model.UseCase;

public class CUCFile implements FileInterface {

	String classContent = "";
	String useCaseContent = "";
	String connectionsContent = "";
	DiagramExpressionModel dem = DiagramExpressionModel.get();
	ArrayList<UseCase> allUseCases = dem.getUseCases();
	ArrayList<paf.model.Class> allClasses = dem.getClasses();
	ArrayList<Connection> allConnections = dem.getConnections();

	protected CUCFile() {}

	@Override
	public void writeToFile(Component c, String fileName) {
		classContent = "<classes>\n";
		for(paf.model.Class cl : allClasses)
			classContent = classContent + "	<class>" + cl.getName() + "</class>\n";
		classContent = classContent + "</classes>\n";

		useCaseContent = "<usecases>\n";
		for(UseCase u : allUseCases)
			useCaseContent = useCaseContent + "	<usecase>" + u.getName() + "</usecase>\n";
		useCaseContent = useCaseContent + "</usecases>\n";

		connectionsContent = "<connections>\n";
		for(Connection co : allConnections) {
			connectionsContent = connectionsContent + "   <connection>\n";
			connectionsContent = connectionsContent + "	<connectionclass>" + co.getConnectedClass().getName() + "</connectionclass>\n";
			connectionsContent = connectionsContent + "	<connectionusecase>" + co.getConnectedUseCase().getName() + "</connectionusecase>\n";
			connectionsContent = connectionsContent + "	<create>" + co.isCreate() + "</create>\n";
			connectionsContent = connectionsContent + "	<read>" + co.isRead() + "</read>\n";
			connectionsContent = connectionsContent + "	<update>" + co.isUpdate() + "</update>\n";
			connectionsContent = connectionsContent + "	<delete>" + co.isDelete() + "</delete>\n";
			connectionsContent = connectionsContent + "   </connection>\n";
		}
		connectionsContent = connectionsContent + "</connections>\n";

		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(fileName + ".cuc"));
			out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
			out.write("<classusecaseconnector>\n");
			out.write(classContent);
			out.write(useCaseContent);
			out.write(connectionsContent);
			out.write("</classusecaseconnector>");
			out.close();
		} catch (IOException e) {
		}
	}
	
	@Override
	public String toString() {
		return "CUC File";
	}
}
